<?php

namespace app\store\controller\market;
use app\store\controller\Controller;
use think\Session;
use app\common\model\SettingLog as SettingLogSettingModel;
use app\factory\MqFactory;

/**
 * 营销设置-分红设置
 * Class Basic
 * @package app\store\controller
 */
class Setting extends Controller
{
    /**
     * 满额包邮设置
     * @return array|bool|mixed
     * @throws \think\exception\DbException
     */
    public function set()
    {

        $nowTime = time();
        $wxapp_id = Session::get('yoshop_store')['wxapp']['wxapp_id'];
        if (!$this->request->isAjax()) {

            $values = db('wxapp_setting')->where(['wxapp_id'=>$wxapp_id])->find();
            if($values){
                $values['start_time'] = date('Y-m-d H:i:s', $values['start_time']);
//                if($values['end_time']<$nowTime){
//                    $values['start_time'] = date('Y-m-d H:i:s', $nowTime);
//                }
            }else{
                $values['status'] = 2;//分红开关 1 开启 2关闭
                $values['start_time'] = date('Y-m-d H:i:s', $nowTime);//开始时间
                $values['money'] = 0;//分红条件
                $values['term'] = 0;//分红周期
                $values['upline'] = 0;//分红上限
                $values['rewardpercent'] = 0;//分红拨比
                $values['moneypercent'] = 0;//零钱比例
                $values['moneypercentstatus'] = 2;//零钱比例开关 1 开启 2关闭
                $values['periods_num'] = 1000;
                $values['real_reward'] = 0;//实物是否参与分红 0 否 1是
            }

            return $this->fetch('set', [
                'values' => $values
            ]);
        }

        //时间判断
        $getTime = strtotime($this->postData('model')['start_time']);
        $endTime =  $getTime+$this->postData('model')['term']*24*60*60;

        $is_exsit = db('wxapp_setting')->where(['wxapp_id'=>$wxapp_id])->find();

        //判断分红周期
        $term = $this->postData('model')['term'];
        if($term<1 || $term>180){
            return $this->renderError('分红周期为1-180');
        }

        //判断分红上限
        $upline = $this->postData('model')['upline'];
        
        if($upline<=0){
            return $this->renderError('分红上限不能小于0');
        }
        
        if($upline>100){
            return $this->renderError('分红上限不能超过100');
        }

        //分红拨比
        $rewardpercent = $this->postData('model')['rewardpercent'];

        if($rewardpercent<3 || $rewardpercent>50){
            return $this->renderError('分红拨比范围为3~50');
        }


        $updateDate = [
            'wxapp_id' => $wxapp_id,
            'money' => $this->postData('model')['money'],//分红条件
            'start_time' => $getTime,//开始时间
            'end_time' => $endTime,//结束时间
            'term' =>$term,//分红周期
            'upline' => $upline,//分红上限
            'rewardpercent' => $this->postData('model')['rewardpercent'],//分红拨比
            'moneypercent' => $this->postData('model')['moneypercent'],//零钱比例
            'moneypercentstatus' => $this->postData('model')['moneypercentstatus'],//零钱比例开关 1 开启 2关闭
            'status' => $this->postData('model')['status'],//分红开关 1 开启 2关闭
            'real_reward' => $this->postData('model')['real_reward'],//实物是否参与分红 0 否 1是

        ];

        $settingLog = new SettingLogSettingModel();

        if($is_exsit){
            //以前的开始时间
            $oldStartTime = $is_exsit['start_time'];
            //以前的结束时间
            $oldEndTime = $is_exsit['end_time'];

            if($getTime!=$oldStartTime){
                //出局处理
                $rmq = MqFactory::instance();

                $data = ['wxapp_id'=>$wxapp_id,'periods_num'=>$is_exsit['periods_num']];

                $rmq->send($data,'divideReceives','divideReceivesLog','divideReceivesLog');

                $updateDate['periods_num'] = $is_exsit['periods_num']+1;
            }else{
                $updateDate['periods_num'] = $is_exsit['periods_num'];
            }

            //未开始
            if($oldStartTime>$nowTime ){


                db('wxapp_setting')->where(['wxapp_id'=>$wxapp_id])->update($updateDate);

            }elseif($oldStartTime<=$nowTime && $oldEndTime>=$nowTime){

                db('wxapp_setting')->where(['wxapp_id'=>$wxapp_id])->update($updateDate);

            }elseif($oldEndTime<$nowTime){

//                if($getTime<$nowTime){
//                    return $this->renderError('时间不能小于当前时间');
//                }

                db('wxapp_setting')->where(['wxapp_id'=>$wxapp_id])->update($updateDate);

            }
            //设备类型
            $deviceType = getDeviceType();
            //写入分红配置日志 start
            $logData = [
                'type'=>1,//1：分红设置  2：会员卡分红设置
                'create_time'=>time(),
                'client'=>"分红设置",
                'deviceType'=>$deviceType,
                'wxapp_id'=>$wxapp_id
            ];
            $settingLog->addData($logData,$updateDate);

        }else{

//            if($getTime<$nowTime){
//                return $this->renderError('时间不能小于当前时间');
//            }

            $insertData = [
                'wxapp_id' => $wxapp_id,
                'money' => $this->postData('model')['money'],//分红条件
                'start_time' => $getTime,//开始时间
                'end_time' => $endTime,//结束时间
                'term' => $this->postData('model')['term'],//分红周期
                'upline' => $this->postData('model')['upline'],//分红上限
                'rewardpercent' => $this->postData('model')['rewardpercent'],//分红拨比
                'moneypercent' => $this->postData('model')['moneypercent'],//零钱比例
                'moneypercentstatus' => $this->postData('model')['moneypercentstatus'],//零钱比例开关 1 开启 2关闭
                'status' => $this->postData('model')['status'],//分红开关 1 开启 2关闭
                'real_reward' => $this->postData('model')['real_reward'],//实物是否参与分红 0 否 1是
                'periods_num' => 1000,

            ];
            //设备类型
            $deviceType = getDeviceType();
            //写入分红配置日志 start
            $logData=[
                'type'=>1,//1：分红设置  2：会员卡分红设置
                'create_time'=>time(),
                'client'=>"分红设置",
                'deviceType'=>$deviceType,
                'wxapp_id'=>$wxapp_id
            ];
            $settingLog->addData($logData,$insertData);

            db('wxapp_setting')->insert($insertData);
        }


        return $this->renderSuccess('操作成功');



    }


    /**
     * 日志列表
     */
    public function log(){

        $wxapp_id = Session::get('yoshop_store')['wxapp']['wxapp_id'];

        $filter = [];

        $param = $this->request->param();
        // 起始时间
        !empty($param['start_time']) && $filter['create_time']  = ['>=',strtotime($param['start_time'])];
        // 截止时间
        !empty($param['end_time']) &&  $filter['create_time']  = ['<',strtotime($param['end_time']) + 86400];

        if(!empty($param['start_time']) && !empty($param['end_time'])){
            $filter['create_time']  = ['between',[strtotime($param['start_time']), strtotime($param['end_time']) + 86400]];
        }

        $list = db('setting_log')
            ->where(['type'=>1,'wxapp_id'=>$wxapp_id])
            ->where($filter)
            ->order(['create_time desc'])
            ->paginate(20, false, [
                'query' => \request()->request()
            ])->each(function($item,$key){
                $item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);
                $item['values'] = json_decode($item['values'],true);
                $item['values']['start_time'] = date('Y-m-d H:i:s',$item['values']['start_time']);
                return $item;
            });
        return $this->fetch('log', [
            'list' => $list
        ]);


    }


}